package com.jiezuo.demos_poi;

import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.List;

/**
 *@Description
 *@Author 庞留杰
 *@Date2024/11/11 8:43
 *@Version V1.0
 **/
public class ApachePoi {

    final static String template = "D:\\data\\poi\\ApachePoi模版.docx";
    final static String generate = "D:\\data\\poi\\ApachePoi生成效果.docx";
    final static String image = "D:\\data\\poi\\image.jpg";

    public static void main(String[] args) throws Exception {
        FileInputStream fis = new FileInputStream(template);
        XWPFDocument doc = new XWPFDocument(fis);
        for (XWPFParagraph p : doc.getParagraphs()) {
            List<XWPFRun> runs = p.getRuns();
            for (XWPFRun r : runs) {
                String text = r.getText(0);
                if (text != null && text.contains("{{image}}")) {
                    r.setText("", 0);
                    FileInputStream is = new FileInputStream(image);
                    r.addBreak();
                    r.addPicture(is, XWPFDocument.PICTURE_TYPE_JPEG, image, Units.toEMU(200), Units.toEMU(200));
                    is.close();
                }
            }
        }
        FileOutputStream fos = new FileOutputStream(generate);
        doc.write(fos);
        fos.close();
    }

}
